import {onMounted, Ref, ref} from "vue";
import {dayjs} from "element-plus";
import solarlunar from 'solarlunar'
import {useAlarmClock} from "../stores/AlarmClock";
import {useSettings} from "../stores/Settings";

export default function () {
  // 展示的时间
  let timertxt: Ref<string> = ref("获取中...")
  // 继续加载
  let continueLoading: Ref<boolean> = ref(true)
  // 农历信息
  let solarlunarinfo: Ref<{}> = ref({})
  // 农历
  let Chinesecalendar: Ref<{}> = ref({})
  // 定时器
  let timer
  // 状态管理
  const store = useAlarmClock()
  const settingstore = useSettings()
  // 当前模式
  const model:Ref<string> = ref('time')

  /**
   * 计算时间
   */
  const computetimer = (): void => {
    if (continueLoading.value) {
      timertxt.value = dayjs(new Date()).format("HH:mm:ss")
      if (store.AlarmClockInfo.length > 0) {
        if (store.AlarmClockInfo.find(x => x.time === timertxt.value && x.state === true)) {
          window.api.openWindowMessage("定时器提醒", "当前时间" + timertxt.value)
        }
      }
    }
  }

  /**
   * 获取下一次的时间
   * @constructor
   */
  const NextTimer = (): void => {
    // 有定时器的话则清空定时器
    if (timer) {
      clearInterval(timer);
      timer = null
    }
    if (!continueLoading.value)
      continueLoading.value = true
    timer = setInterval(() => {
      computetimer()
    }, 1000)
  }

  /**
   * 关闭定时器
   * @constructor
   */
  const StopTimer = (): void => {
    continueLoading.value = false
    clearInterval(timer);
    timer = null;
  }

  /**
   * 倒计时
   * @constructor
   */
  const CountDown = (): void => {
    StopTimer()
    continueLoading.value = true
    // 修改模式
    model.value = 'CountDown'
    // 分钟
    let m:string = settingstore.countdown
    // 秒钟
    let s:string = "00"
    // 定义时间
    timertxt.value = m+":"+s
    // 计算每一秒的时间
    timer = setInterval(()=>{
      if (s==="00" || s==="0"){
        // 当时间大于1分钟时
        if (Number(m)-1>=0){
          m = (Number(m)-1).toString().padStart(2, '0')
          s = "59"
          timertxt.value = m+":"+s
        }
        // 时间走完后
        else{
          StopTimer()
          timertxt.value = "00:00"
        }
      }
      else{
        s = (Number(s)-1).toString().padStart(2, '0')
        timertxt.value = m+":"+s
      }
    },1000)
  }

  /**
   * 恢复时钟
   * @constructor
   */
  const recover = (): void => {
    StopTimer()
    continueLoading.value = true
    NextTimer()
  }

  onMounted((): void => {
    NextTimer()
    const nowDate = new Date()
    const data = solarlunar.solar2lunar(nowDate.getFullYear(), nowDate.getMonth() + 1, nowDate.getDate()) // 时间戳不支持-1
    solarlunarinfo.value = data
    Chinesecalendar.value = data.gzYear + data.animal + "年" + "(" + data.yearCn + ")"
  })

  return {
    timertxt,
    model,
    solarlunarinfo,
    Chinesecalendar,
    continueLoading,
    StopTimer,
    NextTimer,
    CountDown,
    recover
  }
}
